import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { CommonModule } from '@angular/common';
import { LoginService } from '../login/login.service';

@Component({
  selector: 'app-register',
  standalone: true,
  imports: [ReactiveFormsModule, CommonModule],
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent {
  registerForm: FormGroup;
  isLoading = false;
  registerError = '';

  constructor(
    private fb: FormBuilder,
    private loginService: LoginService,
    private router: Router
  ) {
    this.registerForm = this.fb.group({
      username: ['', [Validators.required, Validators.minLength(4)]],
      password: ['', [Validators.required, Validators.minLength(6)]],
      confirmPassword: ['', [Validators.required]]
    }, {
      validators: this.passwordMatchValidator
    });
  }

  passwordMatchValidator(g: FormGroup) {
    const password = g.get('password')?.value;
    const confirmPassword = g.get('confirmPassword')?.value;
    return password === confirmPassword ? null : { 'mismatch': true };
  }

  onSubmit(): void {
    if (this.registerForm.valid) {
      this.isLoading = true;
      this.registerError = '';

      const { username, password } = this.registerForm.value;
      this.loginService.register({ username, password }).subscribe({
        next: () => {
          // 注册成功后自动登录
          this.loginService.login({ username, password }).subscribe({
            next: () => this.router.navigate(['/admin']),
            error: (error) => {
              this.isLoading = false;
              this.registerError = '登录失败：' + (error.message || '请稍后重试');
            }
          });
        },
        error: (error) => {
          this.isLoading = false;
          this.registerError = '注册失败：' + (error.message || '请稍后重试');
        }
      });
    } else {
      Object.keys(this.registerForm.controls).forEach(key => {
        const control = this.registerForm.get(key);
        if (control?.invalid) {
          control.markAsTouched();
        }
      });
    }
  }

  // 获取表单控件的错误状态
  getErrorMessage(controlName: string): string {
    const control = this.registerForm.get(controlName);
    if (control?.errors && control.touched) {
      if (control.errors['required']) {
        return `${this.getFieldName(controlName)}不能为空`;
      }
      if (control.errors['minlength']) {
        const requiredLength = control.errors['minlength'].requiredLength;
        return `${this.getFieldName(controlName)}长度不能少于${requiredLength}个字符`;
      }
      if (controlName === 'confirmPassword' && this.registerForm.errors?.['mismatch']) {
        return '两次输入的密码不一致';
      }
    }
    return '';
  }

  private getFieldName(controlName: string): string {
    const fieldNames: { [key: string]: string } = {
      username: '用户名',
      password: '密码',
      confirmPassword: '确认密码'
    };
    return fieldNames[controlName] || controlName;
  }
}